package lyj.springcloud.controller;

import com.lyj.springcloud.entities.CommonResult;
import com.lyj.threads.SinglePoolParam;
import com.lyj.threads.ThreadPoolManage;
import lyj.springcloud.service.ThreadPoolService;
import lyj.springcloud.task.ThreadTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ThreadPoolTestController {

    @Autowired
    private ThreadPoolService service;

    /**
     * 测试线程池
     * 只是创建多个线程来执行任务，但是与主线程还是属于同步
     */
    @GetMapping("/test/threadpool")
    public CommonResult<String> testThreadPool() {
        SinglePoolParam pool = ThreadPoolManage.getInstance("CONSUMER");
        for (int i =0 ; i < 10 ;i++) {
            // 放入任务并执行
            pool.put(new ThreadTask(i));
        }
        System.out.println("当前活动线程数：" + pool.getExecutor().getActiveCount() );
        System.out.println("当前阻塞队列任务数：" + pool.getExecutor().getQueue().size());
        System.out.println("线程池完成任务数：" + pool.getExecutor().getCompletedTaskCount());
        return new CommonResult<>("success");
    }

    /**
     * 异步执行
     * @return
     */
    @GetMapping("/test")
    public CommonResult<String> test() {
        System.out.println("主线程开始执行。。。。");
        for (int i = 0 ; i < 10 ; i++) {
            ThreadTask paymentThreadTask = new ThreadTask();
            paymentThreadTask.start();
        }
        System.out.println("主线程执行结束。。。。");
        return new CommonResult<>("success");
    }

    /**
     * 异步调用
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/asyncpayment")
    public CommonResult<String> asyncPayment() throws InterruptedException {
        for (int i =0 ; i < 10 ;i++) {
            // 放入任务并执行
            service.asyncPayment();
        }
        return new CommonResult<>( "async doing ........");
    }


}
